﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using OpenAuth.Repository.Domain;
using OpenAuth.App;
using Infrastructure;
using Infrastructure.Cache;
using CCBSign;
using log4net;
using OpenAuth.App.Request;
using OpenAuth.WebApi.Model;
using Microsoft.AspNetCore.Http.Internal;
using Newtonsoft.Json;
using OpenAuth.Hospital;
using OpenAuth.Hospital.Model;

namespace OpenAuth.WebApi.Areas.HisApi.Controllers

{

    /// <summary>
    /// 
    /// </summary>
    [Route("HisApi/[controller]/[action]")]
    [ApiController]
    public class PayBankController : ControllerBase
    {
        private ILog log = LogManager.GetLogger(typeof(PayBankController));
        //缓存
        private ICacheContext cache;
        private readonly QRPayApp qrApp;
        //门诊预交金预充值
        private readonly BMZXX006App bmzxx006App;
        private readonly BMZXX003App bmzxx003App;
        private readonly CGGYW007App cggyw007App;
        private readonly BMZXX009App bmzxx009App;
        //向本地表写入充值记录
        private readonly PayOrderApp payorderApp;
        private readonly PayOrderZYApp payorderZYApp;
        //本地表退款记录
        private readonly RefundOrderApp refundOrderApp;
        private readonly PayToolsApp payToolsApp;
        //患者基本信息
        private readonly CMZXX001App cmzxx001App;
        private readonly CMZXX002App cMZXX002App;
        //private HospitalApi hospitalApi;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_qrApp"></param>
        /// <param name="_payorderApp"></param>
        /// <param name="_refundOrderApp"></param>
        /// <param name="_payToolsApp"></param>
        /// <param name="_bmzxx006App"></param>
        /// <param name="_bmzxx003App"></param>

        public PayBankController(QRPayApp _qrApp, PayOrderApp _payorderApp, PayOrderZYApp _payorderZYApp,/* HospitalApi _hospitalApi,*/ CGGYW007App _cggyw007App, BMZXX009App _bmzxx009App, RefundOrderApp _refundOrderApp, PayToolsApp _payToolsApp, BMZXX006App _bmzxx006App, BMZXX003App _bmzxx003App, CMZXX001App _cmzxx001App, CMZXX002App _cMZXX002App, ICacheContext _cache)
        {
            qrApp = _qrApp;
            bmzxx006App = _bmzxx006App;
            bmzxx003App = _bmzxx003App;
            payorderApp = _payorderApp;
            payorderZYApp = _payorderZYApp;
            //hospitalApi = _hospitalApi;

            payToolsApp = _payToolsApp;
            cggyw007App = _cggyw007App;
            bmzxx009App = _bmzxx009App;
            refundOrderApp = _refundOrderApp;
            cmzxx001App = _cmzxx001App;
            cMZXX002App = _cMZXX002App;
            cache = _cache;
        }

        /// <summary>
        /// 获取付款二维码
        /// </summary>
        /// <param name="patid">患者id</param>
        /// <param name="name">姓名</param>
        /// <param name="phone">手机</param>
        /// <param name="card">卡号</param> 
        /// <param name="amount">金额</param>
        /// <returns></returns>
        [HttpGet]
        public Response GetQR(string patid, string name, string phone, string card, float amount)
        {

            var result = new Response<PaySecond>();
            //返回流水号
            PaySecond paySecond = qrApp.GetQR(patid, name, phone, card, amount, QrType.MZ);
            //本地数据库写入一条数据0=新建订单，1=建行成功，2=卫宁his成功
            payorderApp.Add(new AddOrUpdatePayOrderReq()
            {
                OrderNumber = paySecond.ORDERID,
                bxh = card,
                hzxm = name,
                zfPhone = phone,
                patid = patid,
                zfje = amount,
                zfzt = 0,
                time = DateTime.Now,
            });
            result.Result = new PaySecond
            {
                SUCCESS = "true",
                ORDERID = paySecond.ORDERID,
                QRURL = paySecond.QRURL
            };
            return result;
        }

        private object olock = new object();
        /// <summary>
        /// 建行充值成功返回消息接收
        /// </summary>
        [HttpPost]
        public void CallBack()
        {

            //加上高并发锁
            lock (olock)
            {
                Request.EnableRewind();
                var keys = Request.Query;
                var keys1 = Request.Query.Keys;
                string cc = "";
                foreach (var item in keys1)
                {
                    cc += item + ":" + keys[item].ToString();
                }
                log.Error(cc);
                //公钥
                string pubKey = "30819d300d06092a864886f70d010101050003818b0030818702818100a2a6bee1bcca0660788fe3baf3d402c6598e64e98cf32d59abf3fc26f4175f6c6025124290c1a85ff8216415a8587fe462e865ef836dd2c0e02a3ec627b2e6b1f312ad05b9748a14bdff9b516240e8c3e460b7e36349c92cb112b0dfa30f6442212541acfcefd8de5c82ef2880fc2d2bbc4dddcb2dcfd8c6f8a567733796aa5d020111";
                //签名源串
                string initString = $"POSID={keys["POSID"]}&BRANCHID={keys["BRANCHID"]}&ORDERID={keys["ORDERID"]}&PAYMENT={keys["PAYMENT"]}" +
                    $"&CURCODE={keys["CURCODE"]}&REMARK1={keys["REMARK1"]}&REMARK2={keys["REMARK2"]}&ACC_TYPE={keys["ACC_TYPE"]}&SUCCESS={keys["SUCCESS"]}&ACCDATE={keys["ACCDATE"]}";
                //   $"&TYPE={keys["TYPE"]}&REFERER={keys["REFERER"]}&CLIENTIP={keys["CLIENTIP"]}&ACCDATE={keys["ACCDATE"]}&PAYTYPE={keys["PAYTYPE"]}";没有打开防钓鱼 字段不参与          
                //log.Error(initString + "sign=" + keys["SIGN"]);
                RSASig sign = new RSASig();
                sign.setPublicKey(pubKey);
                bool result = sign.verifySigature(keys["SIGN"], initString);
                log.Error("成功接收到建行消息" + result);

                if (result == true)
                {
                    if (keys["SUCCESS"] == "Y")
                    {
                        // $"{orderId}"
                        string userInfo1 = keys["REMARK1"].ToString().Split(new char[] { '|' })[0];
                        //二维码类型MZ,ZY
                        string qrType = keys["REMARK1"].ToString().Split(new char[] { '|' })[1];
                        //$"{patid}|{phone ?? ""}|{card ?? ""}"
                        string[] userInfo2 = keys["REMARK2"].ToString().Split(new char[] { '|' });
                        //把收到的单号缓存
                        if (cache.Get<String>(userInfo1) == null)
                        {
                            cache.Set(userInfo1, "0", DateTime.Now.AddMinutes(50));
                            log.Debug("写入缓存" + userInfo1);
                        }
                        else
                        {
                            return;
                        }

                        if (qrType == QrType.MZ.ToString())
                        {
                            //支付成功先改成1
                            var order = payorderApp.GetByOrder(userInfo1, userInfo2[0]);
                            //通过sql语句验证流水号是否已经使用
                            var Ex = bmzxx003App.VerifyPtlsh(userInfo1);
                            var Ex1 = bmzxx003App.VerifyPtlsh(userInfo1);
                            var Ex2 = bmzxx003App.VerifyPtlsh(userInfo1);
                            log.Debug("sql语句查验平台流水号" + userInfo1 + "结果：" + Ex + Ex1 + Ex2);

                            if (order.zfzt == 0 && !Ex && !Ex1 && !Ex2)
                            {
                                order.zfzt = 1;

                                payorderApp.Update(order);
                                //查询外部订单接口，过滤重复充值
                                var jg = cggyw007App.QueryOutSideOrder(userInfo1).FirstOrDefault();
                                log.Error("已经判断过his中是否存在本订单，如果重复则建行发回" + userInfo1);
                                var patiend = cmzxx001App.QueryCMZXX001ByCard(userInfo2[2]).FirstOrDefault();
                                //给患者预充值,成功写入单号,单据号
                                var yResult = bmzxx006App.QueryHisPayNo(userInfo2[0], patiend.hzxm).FirstOrDefault();
                                if (yResult != null && yResult.Code == 200)
                                {
                                    order.hisdh = yResult.hisddh;
                                    order.sjh = yResult.jylsh.ToString();
                                    payorderApp.Update(order);
                                }
                                //payorderApp.Update()
                                BMZXX003 temp = new BMZXX003();
                                temp.patid = userInfo2[0];
                                temp.paytype = 2;
                                temp.paymoney = order.zfje ?? 0;
                                temp.paylsh = userInfo1; //支付流水号
                                temp.paytime = "";
                                temp.hisjylsh = yResult.jylsh.ToString();
                                temp.ptlsh = userInfo1;
                                temp.hisddh = yResult.hisddh;
                                //再次判断是否是两次报文同时进来
                                var orderResult = payorderApp.GetByOrder(userInfo1, userInfo2[0]);
                                var Exx = bmzxx003App.VerifyPtlsh(userInfo1);
                                //zai ci pan duan
                                if (!Exx)
                                {


                                    //充值操作调用存储
                                    var cResult = bmzxx003App.PutCardCharge(temp);

                                    //解决充值成功但是没有更新本地库
                                    log.Error("充值完成最后更新充值记录" + cResult.FirstOrDefault().ToJson() + "单号：" + userInfo1);
                                    //充值操作成功
                                    if (cResult != null && cResult.First().Code == 200)
                                    {
                                        order.yjxh = cResult.First().yjxh;
                                        order.zfzt = 2;
                                        log.Error("进入了更新本地库的方法" + cResult.First().ToJson() + "单号：" + userInfo1);
                                        payorderApp.Update(order);
                                    }
                                    //充值操作失败
                                    else
                                    {
                                        log.Error("充值存储过程不成功" + cResult.FirstOrDefault().Message + "单号：" + userInfo1);
                                        //查询外部订单接口，过滤重复充值
                                        var jgg = cggyw007App.QueryOutSideOrder(userInfo1).FirstOrDefault();
                                        if (jgg.zt == 0)
                                        {
                                            order.yjxh = cResult.First().yjxh;
                                            order.zfzt = 2;
                                            payorderApp.Update(order);
                                        }
                                    }
                                }
                            }
                        }
                        else if (qrType == QrType.ZY.ToString())
                        {
                            HospitalApi hospitalApi = new HospitalApi();
                            //支付成功先改成1
                            var order = payorderZYApp.GetByOrder(userInfo1, userInfo2[0]);
                            //通过sql语句验证流水号是否已经使用
                            var Ex = bmzxx003App.VerifyPtlsh(userInfo1);
                            var Ex1 = bmzxx003App.VerifyPtlsh(userInfo1);
                            var Ex2 = bmzxx003App.VerifyPtlsh(userInfo1);
                            log.Debug("sql语句查验平台流水号" + userInfo1 + "结果：" + Ex + Ex1 + Ex2);

                            if (order.zfzt == 0 && !Ex && !Ex1 && !Ex2)
                            {
                                order.zfzt = 1;

                                payorderZYApp.Update(order);
                                //住院预交金预充值
                                var res =JsonConvert.DeserializeObject<PUTZYYJJYSResult>(hospitalApi.PUTZYYJJYS(order.jzlsh, order.hzxm));
                                if (res.success)
                                {
                                    order.hisddh = res.hisddh;
                                    order.yjlsh = res.yjlsh;
                                    payorderZYApp.Update(order);
                                    log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS充值]--充值单号:" + order.OrderNumber + "患者姓名:" + order.hzxm + "预充值成功:修改单号");
                                    //住院预交金充值
                                    var res1 = JsonConvert.DeserializeObject < PUTZYYJJYSResult > (hospitalApi.PUTZYYJJ(new PUTZYYJJ_Input()
                                    {
                                        hzxm = order.hzxm,
                                        jzlsh = order.jzlsh,
                                        yjlsh = res.yjlsh,
                                        hisddh = res.hisddh,
                                        ptlsh = userInfo1,//----------------
                                        zffs = "2",
                                        zfje= order.zfje.ToString() ?? "0",
                                        zflsh = userInfo1,//---------------
                                        zfsj = "",//-----------
                                        lxdh = order.zfPhone,
                                        lxrxm = order.hzxm,
                                        //lxrzjh = order.Id
                                    }));
                                    if (res1.success)
                                    {
                                        order.zfzt = 2;
                                        payorderZYApp.Update(order);
                                        log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS充值]--充值单号:" + order.OrderNumber + ",充值成功");
                                    }
                                    else
                                    {
                                        log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS充值]--充值单号:" + order.OrderNumber + ",充值失败:" + res1.message);
                                    }
                                }
                                else
                                {
                                    log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS充值]--充值单号:" + order.OrderNumber + ",预充值失败:" + res.message);
                                }

                            }
                        }

                    }
                }
            }
        }



        #region 退款写入本地库方法(已测试)

        /// <summary>
        /// 退款写入本地库方法
        /// </summary>
        /// <param name="hzxm">患者姓名</param>
        /// <param name="patid">患者id</param>
        /// <param name="amount">退款金额</param>
        /// <param name="ptlsh">平台流水号(充值的订单号)</param>
        /// <returns></returns>
        [HttpGet]
        public string Refunded(string hzxm, string patid, string amount, string ptlsh)
        {
            //查找患者基本信息
            var patiend = cmzxx001App.QueryCMZXX005ByPID(patid, hzxm).FirstOrDefault();
            if (patiend.cardno != null)
            {
                //获取预交金预充值hisdh yjjxh
                RefundOrderEntity entity = new RefundOrderEntity();
                entity.OrderNumber = UniqueData.Gener("");
                entity.bxh = patiend.cardno;
                entity.hzxm = patiend.hzxm;
                entity.tkje = float.Parse(amount);
                entity.time = DateTime.Now;
                //从his中读取电话可能为空
                entity.tkPhone = patiend.lxdh;
                entity.tkrealName = patiend.hzxm;
                //entity.hisdh = ;
                //entity.yjjxh = ;
                entity.tkNumber = ptlsh;
                entity.patid = patiend.patid.ToString("0");
                entity.tkzt = 1;
                refundOrderApp.Add(entity);
                return new { success = "true", requestId = Guid.NewGuid().ToString(), message = "退款退款申请成功！请等待退款到账" }.ToJson();

            }
            else
            {
                return new { success = "false", requestId = Guid.NewGuid().ToString(), message = "退款写入|没有查询到患者信息" }.ToJson();
            }

        }
        #endregion

        #region 轮询建行退款

        /// <summary>
        /// 轮询建行退款
        /// </summary>
        [HttpGet]
        public int CheckRefundJh()
        {
            //if (Configs.RefundJh)
            //{
            //    return -1;
            //}
            //Configs.RefundJh = true;
            log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "退款定时执行JH");
            var entitys = refundOrderApp.GetListBytkzt(2);
            foreach (var order in entitys)
            {
                try
                {
                    log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[JH退款]--充值单号：" +
                          order.tkNumber + "患者姓名:" + order.hzxm);
                    //查询建行本订单金额
                    string returnStr = payToolsApp.GetOrder(order.tkNumber);
                    //建行订单状态 成功000000
                    var code = xmlToolApp.GetTextBydoc(returnStr, "RETURN_CODE");
                    if (code == "000000")
                    {
                        var pay = xmlToolApp.GetTextBydoc(returnStr, "PAYMENT_MONEY").ToDouble();
                        //已经退款金额
                        var refund = xmlToolApp.GetTextBydoc(returnStr, "REFUND_MONEY").ToDouble();
                        //退款备注
                        var msg = xmlToolApp.GetTextBydoc(returnStr, "RETURN_MSG");
                        //充值金额减去已经退款金额=现在在建行账上还剩余的金额
                        double krefund = pay - refund;
                        //建行端此笔款状态
                        var sate = xmlToolApp.GetTextBydoc(returnStr, "ORDER_STATUS");
                        //真正的退款金额
                        krefund = order.tkje > krefund ? krefund : order.realtkje.ToDouble();
                        //解决卫宁已经退款且请求已经发到建行 但是退款成功的信息没有接收到 第二次退款又过去了 导致的多退
                        //if (refund > 0)
                        //{
                        //    log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[JH退款]--充值单号：" +
                        // order.tkNumber + "患者姓名:" + order.hzxm + "已经退款金额"+ refund + "--修改状态3，条件sate=1");
                        //    return 2;
                        //}
                        //else
                        //{
                        //这里有问题 如果退款不成功 没有显示
                        if (sate == "1")
                        {
                            returnStr = payToolsApp.Refund(krefund, order.tkNumber);
                            //<?xml version="1.0" encoding="UTF-8"?><TX><REQUEST_SN>2021031308581612</REQUEST_SN><RETURN_CODE>WLPT_Err1016</RETURN_CODE><RETURN_MSG>网络连接出错(等待服务器返回)(12030:连接被终止或重置)（如果该笔交易为帐务交易，则处理结果不确定，请先核对明细！）</RETURN_MSG></TX>
                            //判断 这个是建行的错误 不要改成3 加一下判断条件

                            order.tkzt = 3;
                            order.jhtkje = krefund;
                            refundOrderApp.Updateorder(order);
                            log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[JH退款]--充值单号：" +
order.tkNumber + "患者姓名:" + order.hzxm + "--修改状态3，条件sate=1" + "返回报文:" + returnStr);
                            continue;
                        }
                        //0:失败,1:成功,2:待银行确认,3:已部分退款,4:已全额退款,5:待银行确认
                        //else if (sate == "3")
                        //{
                        //    returnStr = payToolsApp.Refund(krefund, order.tkNumber);
                        //}
                        else if (sate == "4")
                        {
                            order.tkzt = 3;
                            order.jhtkje = krefund;
                            refundOrderApp.Updateorder(order);
                            log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[JH退款]--充值单号：" +
                       order.tkNumber + "患者姓名:" + order.hzxm + "--修改状态3，条件sate=4");
                            continue;
                        }
                        //  code = xmlToolApp.GetTextBydoc(returnStr, "RETURN_CODE");
                        //  if (code == "000000")
                        //  {
                        //      order.tkzt = 3;
                        //      order.jhtkje = krefund;
                        //      refundOrderApp.Updateorder(order);
                        //      log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[JH退款]--充值单号：" +
                        //order.tkNumber + "患者姓名:" + order.hzxm + "--修改状态3，条件code=000000");
                        //  }
                        //}


                    }

                }
                catch (Exception e)
                {
                    string strError = "日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "建行退款请求单号：" + order.OrderNumber + "错误信息：" + e.Message + "\r\n";
                    log.Warn(strError);
                    continue;
                }
            }
            //Configs.RefundJh = false;
            return 0;
        }
        #endregion

        #region 卫宁退款轮询

        /// <summary>
        /// 轮询his退款退款
        /// </summary>
        [HttpGet]
        public int CheckRefundHis()
        {
            //if (Configs.RefundHis)
            //{
            //    return -1;
            //}
            Configs.RefundHis = true;
            log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "退款定时执行HIS");
            var entitys = refundOrderApp.GetListBytkzt(1);
            foreach (var order in entitys)
            {

                try
                {
                    log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS退款]--充值单号：" +
                          order.tkNumber + "患者姓名:" + order.hzxm);
                    //查询外部订单结果 1 门诊结算 GETWBDJJG  成功zt=0 不成功zt=1
                    var jg = cggyw007App.QueryOutSideOrder(order.OrderNumber);

                    //返回值：未查到响应数据 没有此笔订单
                    if (jg.FirstOrDefault().hisdh == null && jg.FirstOrDefault().zt == null && jg.Count() == 1)
                    {
                        //给患者预充值,成功写入单号,单据号 即使是退款也需要走一下预充值 需要得到hisddh
                        //var yResult = bmzxx006App.QueryHisPayNo(order.patid, order.hzxm).FirstOrDefault();
                        //if (yResult != null && yResult.Code == 200)
                        //{

                        //    //var reorder = payorderApp.GetByOrder(order.tkNumber, order.patid);
                        //    //reorder.hisdh = yResult.hisddh;
                        //    //reorder.sjh = yResult.jylsh.ToString();

                        //    //payorderApp.Update(reorder);

                        //    //更新退款单字段 his单号和收据号（为nul） 
                        //    //order.yjjxh = yResult.yjjxh;
                        //    order.sjh = yResult.jylsh.ToString();
                        //    order.hisdh = yResult.hisddh;
                        //    refundOrderApp.Updateorder(order.OrderNumber, order.sjh, order.hisdh, order.sjh);
                        //}

                        //查询本地订单
                        var or = payorderApp.GetByOrder(order.tkNumber, order.patid);
                        if (or != null)
                        {
                            //查询门诊患者预交金余额
                            var resultCmzxx002 = cMZXX002App.QueryAccount(new CMZXX002 { patid = order.patid.ToDecimal(), hzxm = order.hzxm });
                            if (resultCmzxx002.Any() && resultCmzxx002.First().Code == 200)
                            {
                                log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS退款]--充值单号：" +
order.tkNumber + "患者姓名:" + order.hzxm + "--[预交金余额]" + resultCmzxx002.First().yjjye + ",退款金额" + order.tkje.ToDecimal());
                                //预交金余额大于退款金额  余额充足
                                if (resultCmzxx002.First().yjjye >= order.tkje.ToDecimal() && resultCmzxx002.First().yjjye > 0)
                                {
                                    var result = bmzxx009App.Refund(new BMZXX009()
                                    {
                                        name = order.hzxm,
                                        patid = order.patid.ToDecimal(),
                                        yjxh = or.yjxh,
                                        ptlsh = order.tkNumber
                                    }).ToList();
                                    log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS退款]--充值单号：" +
order.tkNumber + "患者姓名:" + order.hzxm + "--[预交金余额]" + resultCmzxx002.First().yjjye + ",退款金额" + order.tkje.ToDecimal() + "退款返回值：" + result.First().Message);
                                    if (result.Any() && result.First().Code == 200)
                                    {
                                        order.tkzt = 2;
                                        //退款后返回来得数
                                        order.realtkje = result.First().tfje.ToDouble();
                                        order.sjh = result.First().hisjylsh;
                                        order.hisdh = result.First().tsjh;

                                        order.yjjxh = result.First().tyjxh;
                                        refundOrderApp.Updateorder(order);
                                        log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS退款]--充值单号：" +
                                    order.tkNumber + "患者姓名:" + order.hzxm + "--[没有退款记录]--修改tkzt=2");
                                    }
                                    //这个是给有两笔退款交易，但是第一笔退完后第二笔已经没有钱了，如果再充值还会退
                                    else
                                    {
                                        order.tkopenid = "0";
                                        refundOrderApp.Updateorder(order);

                                    }
                                }
                                //预交金余额小于退款金额 余额不足
                                else if (resultCmzxx002.First().yjjye < order.tkje.ToDecimal() && resultCmzxx002.First().yjjye > 0)
                                {
                                    var result = bmzxx009App.Refund(new BMZXX009()
                                    {
                                        name = order.hzxm,
                                        patid = order.patid.ToDecimal(),
                                        yjxh = or.yjxh,
                                        ptlsh = order.tkNumber
                                    }).ToList();
                                    log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS退款]--充值单号：" +
order.tkNumber + "患者姓名:" + order.hzxm + "--[预交金余额]" + resultCmzxx002.First().yjjye + ",退款金额" + order.tkje.ToDecimal() + "退款返回值：" + result.First().Message);

                                    if (result.Any() && result.First().Code == 200)
                                    {
                                        order.tkzt = 2;
                                        order.realtkje = result.First().tfje.ToDouble();
                                        order.sjh = result.First().hisjylsh;
                                        order.hisdh = result.First().tsjh;

                                        order.yjjxh = result.First().tyjxh;
                                        refundOrderApp.Updateorder(order);
                                        log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS退款]--充值单号：" +
                                    order.tkNumber + "患者姓名:" + order.hzxm + "--[没有退款记录]--修改tkzt=2");
                                    }

                                }
                                //已经退款之后再次点击了一条退款信息
                                else if (resultCmzxx002.First().yjjye == 0)
                                {
                                    order.tkopenid = "0";
                                    refundOrderApp.Updateorder(order);
                                    log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS退款]--充值单号：" +
order.tkNumber + "患者姓名:" + order.hzxm + "--[余额为0得，已经退走得]--修改tkopenid=0");

                                }
                            }

                        }
                    }
                    else
                    {
                        //退款请求没有成功的 0=his成功  1=his不成功
                        if (jg.FirstOrDefault().zt == 1)
                        {
                            var result = bmzxx009App.Refund(new BMZXX009()
                            {
                                name = order.hzxm,
                                patid = order.patid.ToDecimal(),
                                yjxh = order.yjjxh,
                                ptlsh = order.tkNumber
                            }).ToList();
                            if (result.Any() && result.First().Code == 200)
                            {
                                order.tkzt = 2;
                                order.realtkje = result.First().tfje.ToDouble();
                                order.sjh = result.First().hisjylsh;
                                order.hisdh = result.First().tsjh;
                                order.yjjxh = result.First().tyjxh;
                                refundOrderApp.Updateorder(order);
                                log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS退款]--充值单号：" +
                            order.tkNumber + "患者姓名:" + order.hzxm + "--[有退款记录zt等于1]--修改tkzt=2");
                            }
                        }
                        else
                        {
                            order.tkzt = 2;
                            refundOrderApp.Updateorder(order);
                            log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS退款]--充值单号：" +
                                order.tkNumber + "患者姓名:" + order.hzxm + "--[有退款记录zt不等于1]--修改tkzt=2");
                        }
                    }
                }
                catch (Exception e)
                {
                    string strError = "日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "退款请求单号：" + order.OrderNumber + "错误信息：" + e.Message + "\r\n";
                    log.Warn(strError);

                }
            }
            Configs.RefundHis = false;
            return 0;
        }
        #endregion

        #region 轮询建行充值


        /// <summary>
        /// 轮询建行充值
        /// </summary>
        [HttpGet]
        public int CheckRechargeJh()
        {
            //if (Configs.RechargeJh)
            //{
            //    return -1;
            //}
            Configs.RechargeJh = true;
            log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "充值定时执行JH");
            var orders = payorderApp.GetListByzfzt(0);
            foreach (var order in orders)
            {
                try
                {
                    ////怕循环时间太久,每个循环前再确认下状态
                    //if (payorderApp.GetByOrder(order.OrderNumber, order.patid).zfzt != 0)
                    //{
                    //    continue;
                    //}
                    //查询建行本订单金额
                    string returnStr = payToolsApp.GetOrder(order.OrderNumber);
                    log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[JH充值]--充值单号：" + order.OrderNumber + "订单状态" + order.zfzt
                        + "患者姓名" + order.hzxm + "\r\n" + returnStr);
                    //建行订单状态 成功000000
                    var code = xmlToolApp.GetTextBydoc(returnStr, "RETURN_CODE");
                    log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[JH充值]--充值单号:" + order.OrderNumber + "患者姓名:" + order.hzxm + "reutrncode:" + code);
                    if (code == "000000")
                    {
                        var pay = xmlToolApp.GetTextBydoc(returnStr, "PAYMENT_MONEY").ToDouble();
                        //已经退款金额
                        var refund = xmlToolApp.GetTextBydoc(returnStr, "REFUND_MONEY").ToDouble();
                        //退款备注
                        var msg = xmlToolApp.GetTextBydoc(returnStr, "RETURN_MSG");
                        //充值金额减去已经退款金额=现在在建行账上还剩余的金额
                        double krefund = pay - refund;
                        //建行端此笔款状态
                        var sate = xmlToolApp.GetTextBydoc(returnStr, "ORDER_STATUS");
                        if (order.zfje != null && sate == "1" && pay == order.zfje)
                        {
                            order.zfzt = 1;
                            payorderApp.Update(order);
                            log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[JH充值]--充值单号:" + order.OrderNumber + "患者姓名:" + order.hzxm + "充值成功:修改状态");
                        }

                    }
                }
                catch (Exception e)
                {
                    string strError = "日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "建行充值请求单号：" + order.OrderNumber + "错误信息：" + e.Message + "\r\n";
                    log.Warn(strError);
                }

            }
            Configs.RechargeJh = false;
            return 0;
        }
        #endregion

        #region 轮询his充值
        /// <summary>
        /// 轮询his充值
        /// </summary>
        [HttpGet]
        public int CheckRechargeHis()
        {
            //if (Configs.RechargeHis)
            //{
            //    return -1;
            //}
            Configs.RechargeHis = true;
            log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "充值定时执行HIS");
            var orders = payorderApp.GetListByzfzt(1);
            foreach (var order in orders)
            {
                try
                {
                    //怕循环时间太久,每个循环前再确认下状态
                    //if (payorderApp.GetByOrder(order.OrderNumber, order.patid).zfzt != 1)
                    //{
                    //    continue;
                    //}

                    if (string.IsNullOrEmpty(order.hisdh) && string.IsNullOrEmpty(order.sjh))
                    {
                        log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS充值]--充值单号:" + order.OrderNumber + ",预充值,患者姓名:" + order.hzxm);
                        //给患者预充值,成功写入单号,单据号
                        var yResult = bmzxx006App.QueryHisPayNo(order.patid, order.hzxm).FirstOrDefault();
                        if (yResult != null && yResult.Code == 200)
                        {
                            order.hisdh = yResult.hisddh;
                            order.sjh = yResult.jylsh.ToString();
                            payorderApp.Update(order);
                            log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS充值]--充值单号:" + order.OrderNumber + "患者姓名:" + order.hzxm + "预充值成功:修改单号");
                        }
                        else if (yResult != null)
                        {
                            log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS充值]--充值单号:" + order.OrderNumber + ",预充值失败:" + yResult.message);
                        }
                        else
                        {
                            log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS充值]--充值单号:" + order.OrderNumber + ",预充值失败:返回为null");
                        }
                    }
                    log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS充值]--充值单号:" + order.OrderNumber + ",充值,患者姓名:" + order.hzxm);
                    //payorderApp.Update()
                    BMZXX003 temp = new BMZXX003();
                    temp.patid = order.patid;
                    temp.paytype = 2;
                    temp.paymoney = order.zfje ?? 0;
                    temp.paylsh = order.OrderNumber; //支付流水号
                    temp.paytime = "";
                    temp.hisjylsh = order.sjh;
                    temp.ptlsh = order.OrderNumber;
                    temp.hisddh = order.hisdh;

                    var cResult = bmzxx003App.PutCardCharge(temp);
                    if (cResult != null && cResult.First().Code == 200)
                    {
                        order.zfzt = 2;
                        order.yjxh = cResult.First().yjxh;
                        payorderApp.Update(order);
                        log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS充值]--充值单号:" + order.OrderNumber + "患者姓名:" + order.hzxm + "充值成功:修改状态2");
                    }
                    else if (cResult != null)
                    {
                        log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS充值]--充值单号:" + order.OrderNumber + ",充值失败:" + cResult.First().Message);
                    }
                    else
                    {
                        log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS充值]--充值单号:" + order.OrderNumber + ",充值失败:返回为null");
                    }
                }
                catch (Exception e)
                {
                    string strError = "日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "HIS充值请求单号：" + order.OrderNumber + "错误信息：" + e.Message + "\r\n";
                    log.Warn(strError);
                }

            }
            Configs.RechargeHis = false;
            return 0;
        }
        #endregion



        /// <summary>
        /// 付款成功后查询订单是否充值成功用的方法
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="patid"></param>
        /// <returns></returns>
        [HttpGet]
        public string QueryState(string orderId, string patid)
        {

            //log.Debug($"[Action] Query,[参数]{orderId}");
            var order = payorderApp.GetchargeState(orderId, patid);
            if (order)
            {
                return new { SUCCESS = true, Message = "充值成功！" }.ToJson();
            }
            else
            {
                return new { SUCCESS = false, Message = "充值失败！" }.ToJson();
            }

        }
        [HttpGet]
        public string test(string no)
        {
            string returnStr = payToolsApp.GetOrder("202002101550215720214718820");
            var Ex = bmzxx003App.VerifyPtlsh(no);
            return Ex.ToString();
        }
    }
}

